package datastruct.map;

/**
 * @author RunningShrimp
 * @date 2021/5/17  14:06
 * @see <a href=""></a>
 */
public class LinkedListMap<K, V> implements Map<K, V> {
    private final Node head;
    private int size;

    public LinkedListMap() {
        head = new Node();
        size = 0;
    }

    private Node getNode(K key) {
        Node node = head.next;
        while (node != null) {
            if (key.equals(node.key)) {
                return node;
            }
            node = node.next;
        }
        return null;
    }

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if (node == null) {
            head.next = new Node(key, value, head.next);
            size++;
        } else {
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {
        Node prev = head;
        while (prev.next != null) {
            if (key.equals(prev.next.key)) {
                Node delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
                size--;
                return delNode.value;
            }
            prev = prev.next;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        if (node == null) {
            return null;
        }
        return node.value;
    }

    @Override
    public void set(K key, V value) {
        Node node = head.next;
        while (node != null) {
            if (key.equals(node.key)) {
                node.value = value;
            }
            node = node.next;
        }
    }

    @Override
    public int getSize() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return this.size == 0;
    }
    private class Node {
        public K key;
        public V value;
        public Node next;

        public Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key, V value) {
            this(key, value, null);
        }

        public Node() {
            this(null, null, null);
        }

        @Override
        public String toString() {
            return key.toString() + " : " + value.toString();
        }
    }

}
